/*
 * Copyright 2010 Original Author(s)
 * 
 * This file is part of Kommando
 * 
 * Kommando is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Kommando is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Kommando.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.kommando.web.firefox.bookmarks;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.kommando.core.util.Assert;
import org.kommando.web.WebPage;

/**
 * Helper class for working with Firefox bookmarks.
 * 
 * @author Peter De Bruycker
 */
public class Bookmarks {

    private BookmarksParser bookmarksParser = new BookmarksParser();
    private File bookmarks_html;
    private long bookmarksLastModified;
    private List<WebPage> bookmarks = new ArrayList<WebPage>();

    public Bookmarks(File bookmarks_html) {
        Assert.argumentNotNull("bookmarks_html", bookmarks_html);
        Assert.isTrue("bookmarks file doesn't exist", bookmarks_html.exists());

        this.bookmarks_html = bookmarks_html;
    }

    public List<WebPage> getBookmarks() {
        try {
            if (bookmarksChanged()) {
                bookmarksLastModified = bookmarks_html.lastModified();
                bookmarks.clear();
                bookmarks.addAll(bookmarksParser.parseBookmarks(new FileReader(bookmarks_html)));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return bookmarks;
    }

    private boolean bookmarksChanged() {
        return bookmarksLastModified != bookmarks_html.lastModified();
    }

}
